<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" :append-to-body="true" width="65%" @open="handleOpen" @close="handleClose" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-tabs type="border-card">
      <el-tab-pane label="基本信息">
        <div class="tab-wrap">
        <el-form ref="mainFrom" :model="mainFrom" label-width="100px" :rules="mainRules"  size="small">
          <el-row :gutter="20">
            <el-form-item label="病人主诉:" prop="description">
              <el-input type="textarea" rows="4" v-model="mainFrom.description"  placeholder="病人主诉"></el-input>
            </el-form-item>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="图片:">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  accept=".jpg,.jpeg,.png,.gif"
                  :before-upload="beforeUpload"
                  :http-request="uploadUrl"
                  :show-file-list="false"
                >
                  <el-button type="primary"  size="small">{{mainFrom.url?'重新上传':'上传'}}</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="10" v-if="mainFrom.descriptionFile">
              <div class="demo-image__preview">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="mainFrom.descriptionFile"
                  :preview-src-list="srcList">
                </el-image>
              </div>
            </el-col>
          </el-row>
<!--          <el-row :gutter="20">-->
<!--            <el-form-item label="问诊单:" prop="classification">-->
<!--              <el-select v-model="mainFrom.classification"  placeholder="问诊单" class="w-240" multiple @change="handleClassification">-->
<!--                <el-option-->
<!--                  v-for="item in inquiryOptions"-->
<!--                  :key="item.id"-->
<!--                  :label="item.inquiryName"-->
<!--                  :value="item.id"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-row>-->
          <!-- 问诊列表 -->
          <el-row :gutter="20">
            <template >
              <div v-for="(item, index) in inquiryList" :key="index">
                <div class="symptom-wrap">
<!--                  <div class="title">{{ getInqueryName(item.id) }}</div>-->
                  <el-table
                  size="small"
                  :data="item.list"
                  border
                  style="width: 100%">
                  <el-table-column
                    prop="symptomName"
                    label="症状">
                  </el-table-column>
                  <el-table-column
                    label="是否有此症狀">
                    <template slot-scope="scope">
                      <el-radio-group v-model="scope.row.check">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                      </el-radio-group>
<!--                      <el-checkbox v-model="scope.row.check" @change="handleChange(item.id, scope.row.check, scope.$index)"></el-checkbox>-->
                    </template>
                  </el-table-column>
                  </el-table>
                </div>
              </div>
            </template>
          </el-row>
          <el-row :gutter="20">
<!--            <el-button type="primary" size="mini" @click="resultAdd">添加诊断结果</el-button>-->
            <el-button type="success" size="mini" @click="handleDiagnosis">诊断</el-button>
          </el-row>
          <el-row :gutter="20" v-if="diagnosisTable.length > 0">
            <el-table
                size="small"
                :data="diagnosisTable"
                border
                style="width: 100%">
                <el-table-column type="index" label="序号" width="100"/>
                <el-table-column
                  prop="content"
                  label="诊断结果">
                </el-table-column>
                <el-table-column
                  width="90"
                  label="操作">
                  <template slot-scope="scope">
                    <span @click="handleDelete(scope.$index)" class="oper">
                      <i class="el-icon-delete"></i>
                    </span>
                  </template>
                </el-table-column>
              </el-table>
          </el-row>
          <el-row :gutter="20">
            <el-form-item label="诊断结果:" prop="result">
              <div v-if="showText">似为支气管哮喘，建议辅助检查</div>

              <el-checkbox-group v-else v-model="mainFrom.result">
                <el-checkbox :label="item.value" :key="item.value" v-for="item in ruleTypeList">{{item.label}}</el-checkbox>
<!--                <el-button style="margin-left: 20px" type="warning" @click="getMedication">用药</el-button>-->
              </el-checkbox-group>
            </el-form-item>
          </el-row>
          <el-row :gutter="20">
            <el-form-item label="用药:">
              <el-select v-model="mainFrom.medicate"  placeholder="请选择" class="w-240">
                <el-option
                  v-for="item in medicineOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
<!--            <el-form-item label="用药:" prop="medicate">-->
<!--              <el-input type="textarea" rows="4" v-model="mainFrom.medicate"  placeholder="用药"></el-input>-->
<!--            </el-form-item>-->
          </el-row>
<!--          <el-row :gutter="20">-->
<!--            <el-form-item label="医嘱:" prop="charge">-->
<!--              <el-input type="textarea" rows="4" v-model="mainFrom.charge"  placeholder="医嘱"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-row>-->
        </el-form>
        <div class="sub-bottom">
          <el-button type="primary" size="mini" @click="mainFromSubmit">提交</el-button>
        </div>
       </div>
      </el-tab-pane>
      <el-tab-pane label="报告单">
        <div class="tab-wrap">
          <el-form ref="twoFrom" :model="twoFrom" label-width="120px" size="small">
            <el-row :gutter="20">
              <el-form-item label="报告单:">
                <el-select v-model="twoFrom.caseReportCode"  placeholder="报告单" class="w-240">
                <el-option
                  v-for="item in caseReportOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              </el-form-item>
            </el-row>
            <el-row :gutter="20" v-if="twoFrom.caseReportCode">
              <el-col :span="6">
                <el-form-item label="上传报告单:">
                  <el-upload
                    class="avatar-uploader"
                    action="#"
                    accept=".jpg,.jpeg,.png,.gif"
                    :http-request="uploadReport"
                    :show-file-list="false"
                  >
                    <el-button type="primary"  size="small">上传报告单</el-button>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="report-wrap">
              <el-tabs :tab-position="tabPosition" @tab-click="handleTabClick">
                <el-tab-pane :label="tab.reportName" v-for="(tab, index) in reportList" :key="index" >
                  <div class="report-content">
                    <div v-for="(item, index) in tab.reportData" :key="'col' + index" class="col">
                      <div v-for="(k, currentIndex) in item" :key="'cell' + currentIndex" class="cell">
                        <template v-if="currenRowIndex === currentIndex">
                          <template v-if="k.key !== 'save'">
                            <el-input type="text" v-model="k.value" size="mini"></el-input>
                          </template>
                          <template v-else>
                            <span :class="k.key === 'save' ? blue:''" @click="handleSave(tab.uuid, item, index, k, currentIndex)">{{ k.value }}</span>
                          </template>
                        </template>
                        <template v-else>
                          <span :class="k.key === 'edit' ? blue:''" @click="handleEdit(tab.uuid, item, index, k, currentIndex)">{{ k.value }}</span>
                        </template>
                        </div>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-form>
          <div class="sub-bottom">
            <el-button type="primary" size="mini" @click="twoFromSubmit">提交</el-button>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>

</template>
<script>
import { findDiagnostic, uploadFile, getRecordApi,inquiryTableList, getDetail, peportInfoOne,getMedication,getRuleType, peportInfoThree, getDiagnosticId, algorithmType, filetwo, editReportData, diagnosis,medicineList } from "@/api/infoManagement/inqueryRecord";
export default {
  data() {
    return {
      id: this.currentNode,
      dialogFormVisible: false,
      srcList: [],
      showText:false,
      mainFrom: {
        description: '',
        descriptionFile: '',
        result: [],
        medicate:'',
        charge: '',
        id: ''
      },
      mainRules: {
        description: [
          { required: true, message: '请输入病人主诉', trigger: 'blur' }
        ],
        // classification: [
        //   { required: true, message: '请选择问诊单', trigger: 'change' }
        // ],
        // medicate: [
        //   { required: true, message: '请输入用药', trigger: 'blur' }
        // ],
        result:[
          { required: true, message: '请选择诊断结果', trigger: 'blur' }
        ],
        // charge: [
        // { required: true, message: '请输入医嘱', trigger: 'blur' }
        // ]
      },
      ruleTypeList: [],
      inquiryOptions: [],
      inquiryList: [],
      medicineOptions: [],
      diagnosisTable: [],
      // 表单二
      caseReportOptions: [],
      currenRowIndex: -1,
      reportList: [],
      twoFrom: {
        caseReportCode: ''
      }
    }
  },
  props: {
    title: String,
    patientId: String,
    currentNode: String,
  },
  methods: {
    getMedicine(){
      medicineList().then(res=>{
        this.medicineOptions = res.data.data;
      })
    },
    getMedication(){
      const data = {
        stringList:this.mainFrom.result,
        patientId:this.patientId
      }
      getMedication(data).then(res=>{
        if(res.data.data && res.data.data.length){
          this.mainFrom.medicate =res.data.data.map(o=>{
            return o.medication
          }).toString()
          this.mainFrom.charge = res.data.data.map(o=>{
            return o.advice
          }).toString()
        }

      })
    },
    // 打开面板
    handleOpen () {
      this.inquiryTableListFun()
      this.algorithmTypeFun()
      this.findDiagnosticFun()
      // this.getDetailFun()
      this.getRuleType()
      this.getRecord()
      this.getMedicine()
    },
    getRecord(){
      this.inquiryList = []
      getRecordApi(this.patientId).then(res=>{
        let list;
        if(res.data.data.diagnostic!==''){
          list = JSON.parse(JSON.stringify(res.data.data.diagnosticInfo.classificationVOList))

        }else {
          list = JSON.parse(JSON.stringify(res.data.data.inquiryTableVO.classificationVOList))
        }
        let result = []
        if (list && list.length > 0) {
          for (var i = 0; i < list.length; i++) {
            for (var j = 0; j < list[i].symptomListDTOS.length; j++) {
              result.push(list[i].symptomListDTOS[j])
            }
          }
        }
        let obj = {
          list: result
        }
        this.inquiryList.push(obj)
        console.log('inquiryList');
        console.log(this.inquiryList);
      })
    },
    getRuleType(){
      getRuleType().then(res=>{
        this.ruleTypeList = res.data.data;
      })
    },
    // 获取诊断记录
    findDiagnosticFun () {
      findDiagnostic(this.currentNode, 'EDIT')
      .then(res => {
        const resData = JSON.parse(JSON.stringify(res.data.data))
        // 基础信息
        let classification = []
        let diagnosticResult = []
        if (resData.evaluation && resData.evaluation.length > 0) {
          resData.evaluation.forEach(k => {
            classification.push(k.id)
          })
        }
        if (resData.diagnosticResult && resData.diagnosticResult.length > 0) {
          resData.diagnosticResult.forEach(item => {
            diagnosticResult.push({
              content: item
            })
          })
        }
        console.log(resData);
        this.mainFrom = {
          description: resData.description,
          descriptionFile: resData.descriptionFile,
          result:resData.diagnosticResult,
          classification: classification,
          medicate: resData.medicate,
          charge: resData.charge,
          id: resData.id
        }
        this.srcList = [resData.descriptionFile]
        this.inquiryList = resData.evaluation
        // this.diagnosisTable = diagnosticResult;
        // 报告单
        this.reportList = resData.report
      })
    },
    // 获取问诊单下拉框
    inquiryTableListFun () {
      inquiryTableList()
       .then(response => {
        this.inquiryOptions = response.data.data
       })
    },
    // 报告单类型
    algorithmTypeFun () {
      algorithmType()
       .then(res => {
         this.caseReportOptions= res.data.data
       })
    },
    // 诊断
    handleDiagnosis() {
      console.log(this.inquiryList);
      if (this.inquiryList && this.inquiryList.length > 0) {
          let originList = []
          this.inquiryList.forEach(item => {
            item.list.forEach(k => {
              originList.push(k)
            })
          })
          let list = originList.filter(m => m.check)
          let result = []
          if (list.length > 0) {
            originList.forEach(h => {
              let obj = {
                id: h.id,
                value: h.check ? h.check : false
              }
              result.push(obj)
            })
            diagnosis({
              inquiryTableDTOS: result
            })
            .then(res => {
              let results = []
              if (res.data.data && res.data.data.length > 0) {
                this.showText = res.data.data.some(o=>{
                  return o.ruleId == 1771409851120492546
                })
                if(!this.showText){
                  results = res.data.data.map(o=>{
                    return o.asthmaType
                  })
                }
                // res.data.data.forEach(k => {
                //   if(k.value){
                //     results.push(k.asthmaType)
                //   }
                // })
              }
              if(results.length){
                this.mainFrom.result  = results
              }else {
                this.mainFrom.result = []
              }
            })
          }else {
            this.$message.warning('请选择症状!')
          }
      } else {
        this.$message.warning('请选择问诊单!')
      }
    },
    // 面板关闭
    handleClose () {
      this.$emit('getDiagnosticListFun')
      this.srcList = []
      this.id = ''
      this.mainFrom = {
        description: '',
        descriptionFile: '',
        classification: [],
        medicate: '',
        charge: '',
        id: ''
      }
      this.inquiryOptions = []
      this.inquiryList = []
      this.diagnosisTable = []
      this.caseReportOptions = []
      this.currenRowIndex = -1
      this.reportList = []
      this.twoFrom = {
        caseReportCode: ''
      }
      this.dialogFormVisible = false
    },
    // 上传
    uploadUrl(file) {
      const fileName = file.file.name
      const fd = new FormData()
      fd.append('file', file.file)
      uploadFile(fd)
        .then(response => {
          this.$set(this.mainFrom, 'descriptionFile', response.data.data.link)
          this.srcList = [response.data.data.link]
        })
    },
    // 选择问诊单
    handleClassification() {
      this.inquiryList = []
      if (this.mainFrom.classification && this.mainFrom.classification.length > 0) {
        this.mainFrom.classification.forEach(item => {
          this.getDetailFun(item)
        })
      }
    },
    // 获取问诊单的问诊项
    getDetailFun (id) {
      getDetail().then((res) => {
        const list = JSON.parse(JSON.stringify(res.data.data.classificationVOList))
        const originList = JSON.parse(JSON.stringify(this.inquiryList))
        let result = []
        if (list && list.length > 0) {
          for (var i = 0; i < list.length; i++) {
            for (var j = 0; j < list[i].symptomListDTOS.length; j++) {
              result.push(list[i].symptomListDTOS[j])
            }
          }
        }
        let obj = {
          id: id,
          list: result
        }
        if (originList.findIndex(k => k.id === id) === -1) {
          this.inquiryList.push(obj)
        }
      })
    },
    // 是否有症状
    handleChange(id, status, index) {
      let currenIndex = this.inquiryList.findIndex(item => {return item.id === id})
      if (currenIndex > -1) {
        this.inquiryList[currenIndex].list[index]['check'] = status
      }
    },
    // 获取问诊单名称
    getInqueryName(id) {
      let name = ''
      let index = this.inquiryOptions.findIndex(k => {return k.id === id})
      if (index > -1) {
        name = this.inquiryOptions[index].inquiryName
      }
      return name
    },
    // 新增诊断结果
    resultAdd () {
      this.$prompt('请输入诊断结果', '诊断结果', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          this.diagnosisTable.push({
            content: value
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          })
        })
    },
    // 删除诊断结果
    handleDelete (index) {
      this.diagnosisTable.splice(index, 1)
    },
    // 提交基础信息
    mainFromSubmit() {
      this.$refs.mainFrom.validate((valid) => {
        if (valid) {
          let params = {
            description: this.mainFrom.description,
            descriptionFile: this.mainFrom.descriptionFile,
            id: this.mainFrom.id,
            patientId: this.patientId,
            diagnosticResult:this.mainFrom.result,
            evaluation: this.inquiryList,
            medicate: this.mainFrom.medicate,
            charge: this.mainFrom.charge
          }
          peportInfoOne(params)
          .then(() => {
            this.$message.success('保存成功')
          })

        }
      })
    },
    // 上传报告单
    uploadReport(file) {
      const fileName = file.file.name
      const fd = new FormData()
      fd.append('file', file.file)
      fd.append('caseReportCode', this.twoFrom.caseReportCode)
      fd.append('diagnosticId', this.mainFrom.id)
      fd.append('patientId', this.patientId)
      const loading = this.$loading({
        lock: true,
        text: '识别中，请等待!',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      filetwo(fd)
        .then(response => {
          const list = JSON.parse(JSON.stringify(response.data.data.reportData))
          this.reportList.push({
            uuid: response.data.data.id,
            reportImgUrl: response.data.data.reportImgUrl,
            checkDate: response.data.data.checkDate,
            reportName: response.data.data.reportName,
            reportData: list
          })
          loading.close()
        })
        .catch(() => {
          loading.close()
        })
    },
    // 编辑报告单
    handleEdit(uuid, colData, index, cellData, currentIndex) {
      let _this = this
      if (_this.currenRowIndex === -1) {
        if (currentIndex > 0) {
          _this.currenRowIndex = currentIndex
          let tabIndex = _this.reportList.findIndex(k => {return k.uuid === uuid})
          if (tabIndex > -1) {
            if (cellData.key === 'edit') {
              _this.$nextTick(() => {
                _this.reportList[tabIndex].reportData[index][currentIndex].value = '保存'
                _this.reportList[tabIndex].reportData[index][currentIndex].key = 'save'
              })
            }
          }
        }
      } else {
        this.$message.warning('请先保存修改的数据')
      }
    },
    // 保存报告单
    handleSave(uuid, colData, index, cellData, currentIndex) {
      let list = []
      let tabIndex = this.reportList.findIndex(k => {return k.uuid === uuid})
      if (tabIndex > -1) {
        const origin = JSON.parse(JSON.stringify(this.reportList[tabIndex].reportData))
        for (var i = 0; i < origin.length; i++) {
          if (i < origin.length -1) {
            for (var j = 0; j < origin[i].length; j++) {
              if (j === currentIndex) {
                let obj = {
                  code: origin[i][0].key, // 表头code
                  id: origin[i][currentIndex].key, // 表行中的id
                  value: origin[i][currentIndex].value //需要修改的值
                }
                list.push(obj)
              }
            }
          }
        }
        editReportData(list)
        .then(() => {
          this.$message.success('成功')
          let _this = this
          _this.$nextTick(() => {
            _this.reportList[tabIndex].reportData[index][currentIndex].value = '编辑'
            _this.reportList[tabIndex].reportData[index][currentIndex].key = 'edit'
            _this.currenRowIndex = -1
          })
        })
      }
    },
    // 切换tab
    handleTabClick(tab, event) {
      this.currenRowIndex = -1
    },
    // 提交
    twoFromSubmit () {
      this.$refs.mainFrom.validate((valid) => {
        if (valid) {
          this.handleClose()
        } else {
          this.$message.warning('请维护基本信息')
        }
      })
    }
  }
}
</script>
<style scoped>
.container {
  width: 100%;
}
.w-240 {
  width: 240px;
}
.sub-bottom {
  margin: 20px 0;
  text-align: right;
}
.tab-wrap {
  width: 100%;
  height: 450px;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0 10px;
  box-sizing: border-box;
}
.oper {
 display: inline-block;
 width: 50px;
 height: 20px;
 color: #409EFF;
 margin-right: 10px;
 cursor: pointer;
}
.title {
  width: 100%;
  height: 5px;
  line-height: 5px;
  overflow: hidden;
  font-size: 14px;
  color: #409EFF;
  font-weight:  bold;
  padding: 10px 0;
  border-left: 5px solid #409EFF;
  text-indent: 10px;
}
.report-wrap {
  width: 100%;
  overflow: auto;
}
.report-content {
  width: 100%;
  font-size: 12px;
  display: flex;
}
.col {
  display: inline-block;
  width: 90px;
}
.cell {
  width: 90px;
  height: 32px;
  overflow: hidden;
  text-align: left;
}
.blue {
  color: #409EFF;
  cursor: pointer;
}
</style>
